import frappe
import time
import requests
from requests.auth import HTTPBasicAuth

class cache_utils:

    TOKEN_KEY = "sp_api_token"
    TOKEN_TTL = 11 * 3600  # 11小时，单位秒

    @staticmethod
    def get_token():
        """获取缓存中的 token, 如过期则重新请求"""
        cache = frappe.cache()
        token = cache.get(cache_utils.TOKEN_KEY)

        if token:
            return token.decode() if isinstance(token, bytes) else token

        # 向接口请求新的 token
        try:
            url = "https://p.ss-matrix.com/api/auth/oauth2/token?grant_type=password"

            auth = HTTPBasicAuth("test", "test")

            headers = {
                "Content-Type": "application/x-www-form-urlencoded"
            }

            data = {
                "username": "erpadmin",
                "password": "wQPjF6bd+76/FQ==",
                "scope": "server"
            }

            response = requests.post(url, data=data, headers=headers, timeout=10, auth=auth)
            if response.status_code != 200:
                frappe.throw(f"获取Token失败: {response.text}", "TokenRequestError")

            res_json = response.json()
            token = res_json.get("access_token")

            if not token:
                frappe.throw("Token响应中未包含 access_token", "TokenMissing")

            # 缓存 token 并设置过期时间为11小时
            cache.set(cache_utils.TOKEN_KEY, token)
            cache.expire(cache_utils.TOKEN_KEY, cache_utils.TOKEN_TTL)

            return token

        except Exception as e:
            frappe.throw(f"请求Token失败: {frappe.get_traceback()}", "TokenFetchException")
